package com.nx.platform.es.bean.modle.query;

import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ListMultimap;
import com.nx.platform.es.biz.wrapper.parser.StatementOperator;
import com.nx.platform.es.bean.dto.RequestContext;
import org.apache.commons.collections4.MapUtils;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;

import java.util.List;

/**
 * @author
 * @since 2016年10月15日
 */
public class StringNotAnalyzedHandler implements QueryFieldHandler {

    @Override
    public void handle(ImmutableMap<String, ?> fieldConfig, RequestContext context, String fieldFace,
                       StatementOperator operator, String fieldValue, ListMultimap<Boolean, QueryBuilder> queryBuilders) {
        if (Strings.isNullOrEmpty(fieldValue)) {
            return;
        }
        // 记录Query信息(Trace)
        context.getTrace().append("&").append(fieldFace).append(operator.getSymbol()).append(fieldValue);
        //
        String face = MapUtils.getString(fieldConfig, "face");
        String fieldName = MapUtils.getString(fieldConfig, "fieldName");
        Preconditions.checkState(!Strings.isNullOrEmpty(fieldName));
        List<String> words = Splitter.on("|").omitEmptyStrings().splitToList(fieldValue);
        if (words.isEmpty()) {
            return;
        }
        if (words.size() == 1) {
            queryBuilders.put(operator.isSign(),
                    QueryBuilders.termQuery(fieldName, fieldValue));
        } else if (words.size() <= 6) {
            queryBuilders.put(operator.isSign(),
                    QueryBuilders.termsQuery(fieldName, words));
        } else {
            throw new IllegalArgumentException("too more alternatives: field=" + face + ", value=" + fieldValue);
        }

    }

}
